package com.inctech.controller.fileDownload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/file")
public class FileDownloadController {

	@ResponseBody
	@RequestMapping("/download")
	public String download(HttpServletRequest request,
			HttpServletResponse response) {
		//初始化
		URL url = null;
		HttpURLConnection httpUrl = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String fileName = request.getParameter("fileName");
		String fileUrl = "http://localhost/record/"+fileName;
		
		try {
			//建立连接
			url = new URL(fileUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			// 连接指定的资源  
	        httpUrl.connect();
	        long fileLength = httpUrl.getContentLengthLong();
	        
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;fileName="
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			//获取网络输入流
	        bis = new BufferedInputStream(httpUrl.getInputStream());
	        bos = new BufferedOutputStream(response.getOutputStream());

	        byte[] buff = new byte[2048];  
	        int bytesRead;  
	        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
	            bos.write(buff, 0, bytesRead);  
	        }

			// 这里主要关闭。
			bos.close();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpUrl.disconnect();
		}
		return null;
	}
}
